# Logtrack-ng - Module for detecting login messages
# Copyright (C) 2007 Jan Kucera
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
# USA.

=head1 NAME

Logtrack::K3b::Login - modul pro detekci neuspesnych prihlaseni z kerbera

=head1 DESCRIPTION

Module je takrka ekvivalentni s modulem Logtrack::Syslog::Login, oproti nemu 
vsak eviduje jen jeden typ incidentu - zaznam uzivatele_krb. Program tedy neresi
 zavisloti mezi incidenty.

=head2 FUNCTIONS

=over 4

=item accept_login
=item check
=item mail_alert

=cut

package Logtrack::Krb5::Login;
use Logtrack::DBI;

use Exporter;
use Switch;
use Mail::Sender;
use Data::Dumper;
@ISA = qw(Exporter);
@EXPORT = qw(&failed_login &accept_login);

use strict;

our @EXPORT_OK;


=item failed_login
Funkce vlozi, prip. aktualizuje prostrednictvim fce 
Logtrack::DBI::insert_incident zaznam a nasledne overi  mnozstvi
pomoci funkce check, ktere preda id incidentu, kterym byly pozmeny hodnoty
=cut

sub failed_login {
	my ($ref_logtrack,$id_event,@match) = @_;
	my @dirty_incident;
	
	$$ref_logtrack->debug("Spusten Krb_Failed_login\n");
	push @dirty_incident, $$ref_logtrack->{dbi}->insert_incident (
		$id_event,'uzivatele_krb',$match[0]);


	check($ref_logtrack,@dirty_incident);
}

=item
Funkce nejprve zjisti ID incidentu s poctem prihlaseni na uzivatele a nasledne
vyhleda vsechny zaznamy s IP adresou, ktera se autentizovala. Oboji je pak 
predano funkce delete_incident pro mazani zaznamu pres zavislosti.
=cut

sub accept_login {
	my ($ref_logtrack,@match) = @_;
	my ($result);
	my $ref_db = $$ref_logtrack->{dbi}->get_db();
	$$ref_logtrack->debug("Spusten Krb_Accept_login\n");

	$result = $$ref_db->selectrow_hashref('SELECT id FROM incidents 
		WHERE domain = ? AND domain_key = ?', {},'uzivatele_krb',$match[0]);	
	return if(not $result);
	
	$$ref_logtrack->{dbi}->delete_incident($result->{id});
}

sub check {
	my ($ref_logtrack,@dirty_inc) = @_;
	my ($result,$domain_key,$ok);

	my $ref_db = $$ref_logtrack->{dbi}->get_db();
	while(my $id_incident = pop @dirty_inc) {
		$result = $$ref_db->selectrow_hashref('SELECT * FROM incidents
				WHERE id = ?',{},$id_incident);
		
		next if(not defined $result);

		if($result->{count} >= 60 && $result->{domain} eq 'uzivatele_krb') {
 			$$ref_logtrack->debug("!ALERT! Na uzivatele $result->{domain_key}".
 				" se nekdo $result->{count} neuspesne prihlasoval\n");
					
			$ok = mail_alert($ref_db,$result->{id},$result->{domain},
							$result->{domain_key},$result->{count});

			if(not defined $ok) {
				$ref_logtrack->debug("Pozor mail_alert od Krb5::Login::"
					."check neextrahoval z DB u zadne udalosti!\n");
				$ref_logtrack->errstr("Pozor mail_alert od Krb5::Login::"
					."check neextrahoval z DB u zadne udalosti!\n");
			}

			$$ref_logtrack->{dbi}->delete_incident($result->{id});
			next;
		}		
	}
}

=item
Funkce prebira udaje pro vyhledani nahlaseneho incidentu. 
Pomoci ID incident vyextrahuje z tabulky events_incidents ID udalosti, z nich 
posleze ziska originalni zpravu, kterou ulozi do promenne $message_info, ktera 
bude soucasti mailu.
=cut

sub mail_alert {
	my ($ref_db,$id_incident,$domain,$domain_key,$count) = @_;
	my ($message,$message_info,$subject,$result);
	
	my $query = $$ref_db->prepare(
		'SELECT message FROM events WHERE id IN 
			( SELECT id_event FROM events_incidents WHERE id_incident = ? )');
	$query->execute($id_incident);

	if($query->rows) {
		while(my $result = $query->fetchrow_hashref) {
			chomp $result->{message};
			$message_info .= $result->{message} ."\n";
		}
	}
	else {
		return undef;
	}

	$message = 'Dobry den,'. "\n\n". 'bylo detekovano:'. "\n";
	$message .= ' - neuspesna kerberovska prihlaseni'. "\n";
	$message .= 'Prihlasovani se provadelo na tyto uzivatele:'. "\n";
	
	$message .=  ' - '. $domain_key ."\t".$count ."x\n"; 
	$message .= "\n--\n". 'Vypis z logu:'. "\n";
	$message .= $message_info;
		
	$subject = 'Logtrack: Kerberos -> '. $domain_key;

	
	my $email = new Mail::Sender {smtp    => 'localhost',
								from    =>  'logtrack@fi.muni.cz'#,
#                                 replyto =>  'replyto@localhost'
	};
	$email->MailMsg ( {
		to      =>  'xatrix@fi.muni.cz',
		subject =>  $subject,
		msg     =>  $message}
	);
	return 0;
}

1;

__END__
